package com.hooper.cmn.controller;

import com.hooper.cmn.service.DictService;
import com.hooper.hosp.model.cmn.Dict;
import com.hooper.hospital.common.exception.HospitalException;
import com.hooper.hospital.common.result.Result;
import com.hooper.hospital.common.result.ResultCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2022/09/26/19:32
 */
@Api(value = "data dictionary controller")
@Slf4j
@RestController
//@CrossOrigin
@RequestMapping("/admin/dict")
public class DictController {

    @Resource
    private DictService dictService;

    @ApiOperation("find children by id")
    @GetMapping("/findChildren/{id}")
    public Result<List<Dict>> findChildrenById(@PathVariable Long id) {
        List<Dict> list = dictService.findChildrenById(id);
        return Result.ok(list);
    }

    @ApiOperation("export the dict data as an excel file")
    @GetMapping("download")
    public Result<Object> download(HttpServletResponse response) {
        return dictService.downloadDict(response) ? Result.ok() : Result.fail();
    }

    @ApiOperation("import an Excel file and insert the data to the database ")
    @PostMapping("import")
    public Result<Object> importDict(MultipartFile file) {
        if (file == null) {
            throw new HospitalException(ResultCodeEnum.FILE_NOT_FOUND);
        }
        boolean imported = dictService.importDict(file);
        return imported ? Result.ok() : Result.fail();
    }

    @ApiOperation("get hosp level")
    @GetMapping("getDictName/{dictCode}/{value}")
    public String getDictName(@PathVariable String dictCode,
                              @PathVariable String value) {
        return dictService.getDictName(dictCode, value);
    }

    @ApiOperation("get hosp location")
    @GetMapping("getDictName/{value}")
    public String getLocation(@PathVariable String value) {
        return dictService.getDictName(null, value);
    }

    @ApiOperation("get sub node by dict code")
    @GetMapping("/getSubNode/{dictCode}")
    public Result<List<Dict>> getSubNode(@PathVariable String dictCode) {
        List<Dict> subNodeList = dictService.getSubNode(dictCode);
        return subNodeList == null ? Result.fail(ResultCodeEnum.DATA_ERROR)
                : Result.ok(subNodeList);
    }


}
